<template>
  <div>
    <el-dialog
      :title="type === 'add' ? '新增菜品' : '编辑菜品'"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      @close="close"
    >
      <div v-loading="loading" class="app-main-content-box business-store-edit">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="120px"
          prop="icon"
        >
          <el-form-item label="商品名称：" prop="name">
            <el-input v-model="form.name" maxlength="20" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品预览图" prop="icon">
            <div class="cover-img">
              <el-upload
                :limit="3"
                :action="actionUrl"
                :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                :file-list="imgList"
                :before-upload="handleImgBefore"
                :on-success="handleImgSuccess"
                :class="{ hide: imgList.length>=3 }"
                multiple
                accept=".jpg, .jpeg, .JPG, .JPEG, .png, .PNG"
                list-type="picture-card"
              >
                <i slot="default" class="el-icon-plus" />
                <div slot="file" slot-scope="{ file }">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt
                  >
                  <span class="el-upload-list__item-actions">
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleImgRemove(file)"
                    >
                      <i class="el-icon-delete" />
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog title="图片预览" :visible.sync="dialogImageVisible">
                <img width="100%" :src="dialogImageUrl" alt>
              </el-dialog>

              <ul class="upload-tips">
                <li>图片要求：</li>
                <li>1.上传的图片限制文件大小限制1MB，仅支持JPG、PNG格式</li>
                <li>2.建议尺寸：<span class="tag_title">800x800像素，最多可上传3张，第一张为主图</span></li>
              </ul>
            </div>
          </el-form-item>

          <el-form-item label="商品描述：" prop="desc">
            <el-input
              v-model="form.desc"
              :maxlength="60"
              placeholder="请输入商品描述"
            />
          </el-form-item>

          <el-form-item label="商品分类：" prop="categroy">
            <el-select
              v-model="form.categroy"
              class="selectb"
              placeholder="请选择"
            >
              <el-option
                v-for="item in optionsOne"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
            <el-button type="text" size="mini" @click="addClassfication">
              新增分类
            </el-button>
          </el-form-item>
          <el-form-item label="商品类型：">
            <el-input value="主商品" :disabled="true" />
          </el-form-item>
          <!-- <el-form-item
            v-if="!specificationItem"
            label="商品价格："
            prop="price"
            :rules="rules.specPrice"
          >
            <el-input
              v-model="form.price"
              class="priceb"
              placeholder="请输入内容"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>-->
          <!-- <el-form-item
          v-if="specificationItem"-->
          <el-form-item label="商品规格：" class="is-required" prop="itemNum">
            <!-- 规格列表 -->
            <ul>
              <li
                v-for="(item, index) in form.itemNum"
                :key="index"
                class="li-bo"
              >
                <el-form-item
                  style="display: inline-block"
                  :prop="'itemNum.' + index + '.name'"
                  :rules="rules.specName"
                >
                  <el-input
                    v-model="item.name"
                    maxlength="20"
                    class="priceb ai-p"
                    placeholder="请输入规格属性"
                  />
                </el-form-item>
                <el-form-item
                  style="display: inline-block"
                  :prop="'itemNum.' + index + '.price'"
                  :rules="rules.specPrice"
                >
                  <el-input
                    v-model="item.price"
                    class="priceb ai-p"
                    placeholder="请输入规格价格"
                  >
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
                <el-button
                  v-show="form.itemNum.length > 1"
                  type="text"
                  size="mini"
                  round
                  @click="deteleItem(index)"
                >
                  删除
                </el-button>
              </li>
            </ul>
          </el-form-item>

          <el-button
            :disabled="form.itemNum.length >= 5"
            type="text"
            size="mini"
            class="add-left"
            round
            @click="addItem()"
          >
            +添加规格项目
          </el-button>
          <el-form-item
            label="商品排序："
            prop="ranknum"
            :rules="rules.ranknum"
          >
            <el-input
              v-model.number="form.ranknum"
              placeholder="请输入排序号，数字越小越靠前"
              @input="value = value.replace(/[^0-9]/g, '')"
            />
          </el-form-item>
          <el-form-item label="商品属性：" prop="cloum">
            <el-select
              v-model="form.cloum"
              :multiple="true"
              :multiple-limit="3"
              class="selectb"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="赠送商品：">
            <el-button
              :disabled="form.itemNum.length >= 5"
              type="text"
              size="mini"
              class
              round
              @click="openChoose"
            >
              +添加赠送
            </el-button>
            <span class="tag_title">赠品最多支持添加10种</span>
          </el-form-item>
          <div class="free_list">
            <el-table
              :data="form.mgrItemGifts"
              min-height="50"
              max-height="300"
              border
              style="width: 100%"
            >
              <el-table-column width="50" align="center">
                <template slot-scope="scope">
                  <i
                    class="el-icon-close"
                    style="font-weight: bold"
                    @click="deleteFree(scope.$index)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="sellgiftName"
                label="赠送商品名称"
                width="140"
                align="center"
              />
              <el-table-column align="center">
                <template slot="header">
                  规则配置
                  <el-tooltip placement="top">
                    <div slot="content">
                      1笔订单，同一商品满足门槛后仅送一次，不重复送
                      <br>
                      1笔订单，多个商品分别满足门槛，则多个商品均送设置的份数
                    </div>
                    <div class="el-icon-question" />
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <div>
                    <ul>
                      <li
                        v-for="(item, index) in scope.row.rules"
                        :key="index"
                        class="rule_list"
                      >
                        每购买主角商品
                        <el-input
                          v-model.number="item.itemNum"
                          class="rule_input"
                          placeholder="请输入规格价格"
                          size="mini"
                          @blur="changeInput($event, scope.$index, index, 1)"
                        >
                          <template slot="append">份</template>
                        </el-input>
                        ， 赠送
                        <el-input
                          v-model="item.giftNum"
                          class="rule_input"
                          placeholder="请输入规格价格"
                          size="mini"
                          :rules="rules.giftnum"
                          @blur="changeInput($event, scope.$index, index, 2)"
                        >
                          <template slot="append">份</template>
                        </el-input>
                        <el-button
                          v-if="scope.row.rules.length > 1"
                          type="text"
                          @click="addAndDelRule(1, scope.$index, index)"
                        >
                          删除
                        </el-button>
                      </li>
                    </ul>
                    <div class="rule_add">
                      <el-button
                        type="text"
                        @click="addAndDelRule(2, scope.$index)"
                      >
                        <i class="el-icon-plus" />
                        添加规则
                      </el-button>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form-item
            label="商品分享文案设置："
            label-width="130"
            prop="shareText"
          >
            <el-input
              v-model="form.shareText"
              :maxlength="30"
              placeholder="请输入商品分享文案"
            />
          </el-form-item>
            <div style="color: #c1c1c1;margin-bottom:20px;">默认：新注册会员获取更多优惠</div>

          <el-button
            class="add-left"
            size="small"
            round
            @click="dialogVisible = false"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            size="small"
            round
            @click="addComfim('form')"
          >
            保存
          </el-button>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog title="选择赠品" :visible.sync="showChoose" width="50%" @close="colseFree">
      <div class="choose_content">
        <div class="top_form">
          <div class="left">
            <div class="title">商品名称</div>
            <div class="input">
              <el-input
                v-model="searchName"
                size="medium"
                placeholder="请输入赠品名称"
              />
            </div>
          </div>
          <div class="right">
            <el-button size="medium" @click="searchFree()">查询</el-button>
            <el-button size="medium" type="info" @click="searchFree(1)">
              重置
            </el-button>
          </div>
        </div>
        <div class="choose_pro">
          <div class="title">最多选择【10】个</div>
          <div class="table">
            <el-table
              :data="freeList"
              max-height="400"
              border
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                label="赠送商品名称"
                align="center"
              />
              <el-table-column align="center" label="商品主图">
                <template slot-scope="scope">
                  <div class="choose_img">
                    <img :src="`${fileBaseUrl + scope.row.image}`" alt>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                width="80"
                label="价格"
                prop="price"
              />
              <el-table-column width="80" align="center" label="选择">
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.isChecked"
                    @change="chooseFreePro($event, scope.row, scope.$index)"
                  >
                    {{ scope.row.isChecked == true ? "已选择" : "选择" }}
                  </el-checkbox>
                </template>
              </el-table-column>
            </el-table>
            <pagination-direction
              v-if="freeList.length > 0"
              :config="paginationConfig2"
              @sizeschange="getFreeList()"
              @pagechange="getFreeList()"
            />
          </div>
        </div>
      </div>
      <span slot="footer" class="choose_dialog_footer">
        <el-button type="primary" :disabled="form.mgrItemGifts.length>10" size="mini" @click="confirmFreePro()">
          确 定（已选{{ form.mgrItemGifts.length }}件）
        </el-button>
        <el-button size="mini" @click="colseFree()">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import {
  addGoods,
  searAllchClassiFication,
  searchAttributes,
  addClassiFication,
  searchGoodsByOne,
  queryFreeList,
  updateGoods
} from '@/views/wcyModule/api/restaurant'
import { validateStrLen, validateMoney } from '@/utils/validate.js'
import { getShopInfo, createShop, updateShop } from '@/api/shop'
import message from '@/store/modules/message'
export default {
  data() {
    /**
     * 表单校验方法相关
     */
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品名称'))
      } else if (!validateStrLen(value, 20)) {
        callback(new Error('长度不超过10个汉字或20个字符'))
      } else {
        callback()
      }
    }
    const validateDesc = (rule, value, callback) => {
      if (!validateStrLen(value, 60)) {
        callback(new Error('长度不超过30个汉字或60个字符'))
      } else {
        callback()
      }
    }
    const validateSharetext = (rule, value, callback) => {
      if (!validateStrLen(value, 30)) {
        callback(new Error('长度不超过15个汉字或30个字符'))
      } else {
        callback()
      }
    }

    // 金钱校验
    const validateRmb = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入金额'))
      } else if (!validateMoney(value)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else if (value - 999999.99 > 0) {
        callback('超过限额999999.99')
      } else {
        callback()
      }
    }

    return {
      // 配置

      showChoose: false,
      hideUpload: false,
      resolve: null,
      reject: null,
      type: 'add',
      shopId: '',
      goodsId: '',
      chooseForm: {
        keyword: ''
      },
      //  状态
      dialogVisible: false,
      loading: false,
      // 数据
      // type: 'add',
      // specificationItem: false,
      itemNum: [],
      optionsOne: [],
      options: [],
      value: '',
      catevalue: '',
      /**
       * 表单校验字段相关
       */
      rules: {
        // 名称
        name: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        specName: [
          {
            required: true,
            message: '请输入规格属性',
            trigger: ['blur', 'change']
          }
        ],
        ranknum: [
          {
            required: true,
            message: '请输入商品排序',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^[0-9|\\.]/,
            message: '请输入整数'
          }
        ],
        giftnum: [
          {
            required: true,
            message: '请输入数量',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^[0-9|\\.]/,
            message: '请输入整数'
          }
        ],
        specPrice: [
          {
            required: true,
            validator: validateRmb,
            trigger: ['blur', 'change']
          }
        ],
        desc: [
          {
            required: false,
            validator: validateDesc,
            trigger: ['blur', 'change']
          }
        ],
        categroy: [
          {
            required: true,
            message: '请选择分类',
            trigger: ['blur', 'change']
          }
        ],
        shareText: [
          {
            required: false,
            validator: validateSharetext,
            trigger: ['blur', 'change']
          }
        ]
      },
      loading: false,
      actionUrl: imgUploadUrl,
      uploadHeaders: {},
      form: {
        icon: '',
        name: '',
        desc: '',
        price: '',
        categroy: '',
        cloum: [],
        itemNum: [],
        mgrItemGifts: [],
        status: 1,
        ranknum: 1,
        shareText: ''
      },
      freeList: [],
      freeNum: 0,

      dialogImageUrl: '',
      dialogImageVisible: false,
      disabled: false,
      imgList: [],
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      paginationConfig2: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      searchName: ''
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  methods: {
    handleImgBefore(file) {
      return this.beforeUploadImg(file, this, 1000, 1000, 1)
    },

    handleImgSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.imgList = fileList
        this.hideUpload = this.imgList.length >= 3
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.msg)
      }
    },

    handleImgRemove(file) {
      this.imgList.forEach((el, index) => {
        if (el.uid == file.uid) {
          this.imgList.splice(index, 1)
        }
      })
      this.hideUpload = this.imgList.length >= 3
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    editData() {
      searchGoodsByOne({ id: this.goodsId, shopId: this.shopId }).then(
        (res) => {
          if (res.code === 0) {
            this.imgList = []
            this.form.name = res.data.name
            this.form.desc = res.data.description
            this.form.icon = res.data.imageName
            this.form.status = res.data.status
            this.form.shareText = res.data.shareText || ''
            res.data.mgrItemGifts.forEach((el, index) => {
              el.rules = JSON.parse(el.rules)
            })
            res.data.itemImages.split(',').forEach((v) => {
              this.imgList.push({
                response: { code: 0, data: { path: v } },
                url: this.fileBaseUrl + v
              })
            })
            this.form.mgrItemGifts = res.data.mgrItemGifts
            this.shopId = res.data.shopId
            this.$set(this.form, 'ranknum', res.data.ranknum)
            // if (res.data.specList[0].name === "DEFAULT") {
            //   this.form.price = res.data.specList[0].price / 100;
            // } else {
            this.form.itemNum = []
            const list = res.data.specList
            list.forEach((v) => {
              this.form.itemNum.push({
                name: v.name,
                price: (v.price / 100).toFixed(2)
              })
            })
            // this.specificationItem = true;
            // }
            searAllchClassiFication(this.shopId).then((rect) => {
              this.optionsOne = []
              if (rect.code === 0) {
                const params = rect.data.row
                params.forEach((v, i) => {
                  this.optionsOne.push({
                    value: v.name,
                    label: v.name,
                    id: v.id
                  })
                  if (v.id === res.data.classifyId) {
                    this.form.categroy = v.id
                  }
                })
              }
            })
            searchAttributes(this.shopId).then((results) => {
              this.options = []
              if (results.code === 0) {
                this.form.cloum = []
                const list = results.data
                const oldList = res.data.attrs.reverse()
                list.map((v, i) => {
                  this.options.push({ value: v.name, label: v.name, id: v.id })
                })
                oldList.map((v, i) => {
                  this.form.cloum.push(v.id)
                })
              }
            })
            console.log(this.form)
          }
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
        }
      )
    },

    open(type, id, mid) {
      if (type === 'add') {
        this.type = type
        this.shopId = id
        // this.specificationItem = false;
        this.form.itemNum = [{ name: '', price: '' }]
        this.initData()
      } else if (type === 'edit') {
        this.type = type
        this.goodsId = id
        this.shopId = mid
        this.editData()
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },
    colseFree() {
      this.showChoose = false
      this.freeNum = 0
      this.paginationConfig2.page = 1
    },

    close() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
      this.loading = false
      this.specificationItem = false
      this.form = {
        icon: '',
        name: '',
        desc: '',
        price: '',
        categroy: '',
        cloum: [],
        itemNum: [{ name: '', price: '' }],
        mgrItemGifts: [],
        status: 1,
        ranknum: 1,
        shareText: ''
      }
      this.$refs.form.clearValidate()
    },

    // 保存添加
    addComfim(form) {
      this.$refs[form].validate((valid) => {
        console.log(valid)
        if (valid) {
          const {
            imgList,
            form: {
              mgrItemGifts,
              categroy,
              desc,
              status,
              name,
              ranknum,
              shareText,
              itemNum
            },
            specificationItem,
            goodsId,
            shopId
          } = this
          if (imgList.length < 1) {
            this.$message.error('请上传商品图片再进行保存')
            return
          }
          const attrs = []
          const specList = []
          const imgStr = []
          // if (specificationItem === true) {
          itemNum.forEach((v) => {
            specList.push({
              name: v.name,
              price: this.$math.mul(v.price, 100, 0)
            })
          })
          // }
          // else if (specificationItem === false) {
          //   specList.push({
          //     name: "DEFAULT",
          //     price: this.$math.mul(this.form.price, 100, 0),
          //   });
          // }
          // 获取上传的商品图片
          imgList.forEach((e) => {
            if (e.response.code == 0 && e.status == 'success') {
              imgStr.push(e.response.data.path)
            }
          })
          this.form.cloum.forEach((v) => {
            attrs.push({ id: v })
          })
          if (mgrItemGifts && mgrItemGifts.length > 0) {
            mgrItemGifts.forEach((el, index) => {
              el.ranknum = index
              el.rules = JSON.stringify(el.rules)
            })
          }

          const params = {
            attrs: attrs,
            itemImages: imgStr.toString(),
            imageUrl: imgStr[0],
            itemType: 'MAIN',
            mgrItemGifts: mgrItemGifts,
            classifyId: categroy,
            description: desc,
            imageName: imgStr[0],
            status,
            name,
            ranknum,
            shopId,
            specList: specList,
            shareText: shareText || '',
            id: goodsId !== '' ? goodsId : ''
          }

          if (this.type === 'add') {
            console.log(params)
            addGoods(params).then((res) => {
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve()
                this.close()
              }
            })
          } else {
            updateGoods(params).then((res) => {
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve()
                this.close()
              }
            })
          }
          this.imgList = []
        }
      })
    },

    // 新建分类
    addClassfication() {
      this.$prompt('请输入分类名称', '新建分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          const data = {
            isValid: true,
            name: value,
            shopId: this.shopId,
            title: value
          }
          addClassiFication(data).then((res) => {
            if (res.code === 0) {
              this.initData()
            }
          })
          this.$notify({
            title: '成功',
            message: '新增分类: ' + value,
            type: 'success',
            duration: 2000,
            offset: 40
          })
        })
        .catch(() => {})
    },

    // 获取数据
    initData() {
      searAllchClassiFication(this.shopId).then((res) => {
        this.optionsOne = []
        if (res.code === 0) {
          const params = res.data.row
          params.map((v, i) => {
            this.optionsOne.push({ value: v.name, label: v.name, id: v.id })
          })
        }
      })
      searchAttributes(this.shopId).then((res) => {
        this.options = []
        if (res.code === 0) {
          const list = res.data
          list.map((v, i) => {
            this.options.push({ value: v.name, label: v.name, id: v.id })
          })
        }
      })
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    // 删除规格
    deteleItem(index) {
      this.form.itemNum.splice(index, 1)
      // if (this.form.itemNum.length === 0) {
      //   this.specificationItem = false;
      // }
    },

    // 添加规格
    addItem() {
      this.$refs.form.clearValidate(['price'])
      // this.specificationItem = true;
      this.form.itemNum.push({ name: '', price: '' })
    },
    // 删除或者增加规则配置
    addAndDelRule(type, index, index1) {
      if (type == 1) {
        console.log(type, index, index1)
        this.form.mgrItemGifts[index].rules.splice(index1, 1)
      } else {
        let newObj = { giftNum: 1, itemNum: 1 }
        if (this.form.mgrItemGifts[index].rules.length <= 0) {
          this.form.mgrItemGifts[index].rules.push(newObj)
        } else {
          const maxNum = Math.max.apply(
            Math,
            this.form.mgrItemGifts[index].rules.map((item) => {
              return item.itemNum
            })
          )
          newObj = { giftNum: 1, itemNum: maxNum + 1 }
          this.form.mgrItemGifts[index].rules.push(newObj)
        }
      }
    },
    // 删除赠品
    deleteFree(index) {
      this.$confirm('是否删除此赠品?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true
      }).then(() => {
        this.form.mgrItemGifts.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 打开选择赠送弹窗
    openChoose() {
      this.getFreeList()
      this.showChoose = true
    },
    getFreeList() {
      const { form: { mgrItemGifts }, shopId, paginationConfig2: { page = 1, pageSize = 10 }, searchName } = this
      queryFreeList({
        shopId,
        itemType: 'GIFT',
        name: searchName,
        pageNum: page,
        pageSize,
        status: 1
      }).then((res) => {
        const { row } = res.data
        this.paginationConfig2.total = res.data.total
        this.paginationConfig2.page = res.data.pageNum
        if (row.length > 0) {
          row.forEach((e) => {
            e.isChecked = false
            if (mgrItemGifts.length > 0) {
              mgrItemGifts.forEach((res) => {
                if (res.sellgiftId == e.id) {
                  e.isChecked = true
                  return
                }
              })
            }
          })
        }
        this.freeList = row
        this.computedFreeNum()
      })
    },
    searchFree(type) {
      if (type == 1) this.searchName = ''
      this.paginationConfig2.page = 1
      this.getFreeList()
    },
    // 计算已经被勾选的赠送商品数量
    computedFreeNum() {
      this.freeNum = 0
      this.freeList.forEach((el) => {
        el.isChecked == true ? this.freeNum++ : ''
      })
    },
    // 赠品勾选事件
    chooseFreePro(e, data, index) {
      this.freeList[index].isChecked = e
      this.computedFreeNum()
      const { freeList, form: { mgrItemGifts } } = this
      freeList.forEach((ele, index) => {
        if (mgrItemGifts.every((res) => res.sellgiftId != ele.id && ele.isChecked == true)) {
          const newObj = {
            sellgiftId: ele.id,
            sellgiftName: ele.name,
            rules: [{ giftNum: 1, itemNum: 1 }]
          }
          this.form.mgrItemGifts.push(newObj)
        }
        mgrItemGifts.forEach((el, idx) => {
          if (el.sellgiftId == ele.id && ele.isChecked == false) {
            this.form.mgrItemGifts.splice(idx, 1)
          }
        })
      })
    },

    // 赠品弹窗确认事件
    confirmFreePro() {
      // mgrItemGifts 商品规则列表
      // freeList 赠品列表
      // const {freeList,form: { mgrItemGifts },} = this;
      // freeList.forEach((ele, index) => {
      //   if ( mgrItemGifts.every((res) => res.sellgiftId != ele.id && ele.isChecked == true)) {
      //     const newObj = {
      //       sellgiftId: ele.id,
      //       sellgiftName: ele.name,
      //       rules: [{ giftNum: 1, itemNum: 1 }],
      //     };
      //     this.form.mgrItemGifts.push(newObj);
      //   }
      //   mgrItemGifts.forEach((el, idx) => {
      //     if (el.sellgiftId == ele.id && ele.isChecked == false) {
      //       this.form.mgrItemGifts.splice(idx, 1);
      //     }
      //   });
      // });
      this.showChoose = false
    },

    /**
     * 按钮组
     */
    // 图片上传
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.icon = res.data.path
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.msg)
      }
    },

    // 上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 1000, 1000, 1)
    },
    changeInput(e, rowIndex, index, type) {
      const { rules } = JSON.parse(
        JSON.stringify(this.form.mgrItemGifts[rowIndex])
      )
      const { value } = e.target
      const patt = new RegExp(/^[0-9|\\.]/)
      if (!value) {
        type == 1
          ? (this.form.mgrItemGifts[rowIndex].rules[index].itemNum = 0)
          : (this.form.mgrItemGifts[rowIndex].rules[index].giftNum = 0)
        return
      } else if (!patt.test(value)) {
        type == 1
          ? (this.form.mgrItemGifts[rowIndex].rules[index].itemNum = 0)
          : (this.form.mgrItemGifts[rowIndex].rules[index].giftNum = 0)
        return
      }
      if (type == 1) {
        const maxNum =
          Math.max.apply(
            Math,
            rules.map((item) => {
              return item.itemNum
            })
          ) + 1
        rules.forEach((ele, inex) => {
          if (inex != index) {
            if (ele.itemNum == value) {
              this.$message.error(
                '输入的主商品数量已存在，不能存在相同的主商品数量，已帮您修改'
              )
              this.form.mgrItemGifts[rowIndex].rules[index].itemNum = maxNum
            }
          }
        })
      } else {
        this.form.mgrItemGifts[rowIndex].rules[index].giftNum = value
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.business-store-edit {
  .el-input,
  .el-textarea,
  .el-select {
    width: 70%;
    max-width: 600px;
  }

  .cover-img {
    // display: flex;
    align-items: center;
    .app-uploader-img-plus {
      flex: 0 0 auto;
    }
  }

  .app-uploader-img-plus {
    width: 180px;
    height: 180px;
    .app-uploader-img-plus-icon {
      font-size: 36px;
      color: #8c939d;
      width: 180px;
      height: 180px;
      line-height: 180px;
      text-align: center;
    }
    .avatar {
      width: 180px;
      height: 180px;
      display: block;
    }
  }
  .upload-tips {
    margin: 10px 0px;
    li {
      margin: 5px 0;
      font-size: 14px;
      line-height: 16px;
      color: $dark-font-color;
    }
  }
}
.free_list {
  margin-bottom: 22px;
  overflow: auto;
}
.selectb {
  // width: 460px !important;
}
.priceb {
  width: 200px !important;
}
.add-left {
  margin-left: 120px;
  margin-bottom: 22px;
}
.add-item {
  margin-left: -80px;
  margin-bottom: 22px;
}
.ai-p {
  margin-right: 20px;
}
.li-bo {
  margin-bottom: 20px;
}
.rule_list {
  margin-bottom: 10px;
  .rule_input {
    max-width: 120px;
  }
}
.rule_add {
  width: 100%;
  display: flex;
  padding-left: 5px;
}
.choose_dialog_footer {
  width: 100%;
  display: flex;
  justify-content: center;
}
.tag_title{
  font-size: 14px;
  color: #9e9e9e;
}
.choose_content {
  .top_form {
    display: flex;
    > .left {
      display: flex;
      align-items: center;
      margin-right: 30px;
      .title {
        font-weight: bold;
        margin-right: 20px;
      }
      .input {
        min-width: 250px;
      }
    }
  }
  .choose_pro {
    margin-top: 20px;
    .title {
      color: #bbbbbb;
      margin-bottom: 20px;
    }
  }
  .choose_img {
    width: 80px;
    height: 80px;
    overflow: hidden;
    margin: 0 auto;
  }
}
/deep/.hide .el-upload--picture-card {
  display: none;
}
</style>
